package im.composer.audioservers.rmi;

import java.nio.FloatBuffer;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import org.jaudiolibs.audioservers.AudioClient;
import org.jaudiolibs.audioservers.AudioConfiguration;

public class RmiAudioAdapter implements AudioClient {

	private final AudioTerminal terminal;

	private RmiAudioAdapter(AudioTerminal terminal) {
		this.terminal = terminal;
	}
	
	public static RmiAudioAdapter lookup(String host,String path) throws Exception{
		return lookup(host,Registry.REGISTRY_PORT,path);
	}
	public static RmiAudioAdapter lookup(String host,int port,String path) throws Exception{
		Registry myRegistry = LocateRegistry.getRegistry(host,port);
		AudioTerminal terminal = (AudioTerminal) myRegistry.lookup(path);
		return new RmiAudioAdapter(terminal);
	}

	@Override
	public void configure(AudioConfiguration context) throws Exception {
		terminal.configure(context);
	}

	@Override
	public boolean process(long time, List<FloatBuffer> inputs, List<FloatBuffer> outputs, int nframes) {
		try {
			List<float[]> out = terminal.audioExchange(time, FloatBufferListTool.convertBuf2Arr(inputs), nframes);
			int n = Math.min(outputs.size(), out.size());
			for(int i=0;i<n;i++){
				outputs.get(i).put(out.get(i));
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public void shutdown() {
	}

}
